package cn.itcast.oa.action;

import java.util.HashSet;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import cn.itcast.oa.base.BaseAction;
import cn.itcast.oa.base.ModelDrivenBaseAction;
import cn.itcast.oa.model.Privilege;
import cn.itcast.oa.model.Role;
import com.opensymphony.xwork2.ActionContext;

@SuppressWarnings("serial")
@Controller
@Scope("prototype")
public class RoleAction extends ModelDrivenBaseAction<Role>{
	   
	  private Long[] privilegeIds;
	  
       public String add() throws Exception{
    	   roleService.save(model);
    	   return "tolist";
       }
       
       public String delete()throws Exception{
    	   roleService.delete(model.getId());
    	   return "tolist";
       }
       
       public String list() throws Exception{
    	  
		List<Role> roles=roleService.findAll();
		ActionContext.getContext().put("roles", roles);
    	   return "list";
       }
       
       public String addUI() throws Exception{
    	   return "addUI";
       }
       
       public String editUI() throws Exception{
    	   Role role=roleService.getById(model.getId());
    	   ActionContext.getContext().getValueStack().push(role);
    	   return "editUI";
       }
       
       public String edit() throws Exception{
    	   Role role=roleService.getById(model.getId());
    	   role.setName(model.getName());
    	   role.setDescription(model.getDescription());
;          roleService.update(role);
    	   return "tolist";
       }
       public String setPrivilegeUI() throws Exception{
    	   List<Privilege> topPrivilegeList=privilegeService.findTopList();
    	   ActionContext.getContext().put("topPrivilegeList", topPrivilegeList);
    	   
    	   Role role=roleService.getById(model.getId());
    	   ActionContext.getContext().put("role", role);
    	   System.out.println("---------------------");
   	  
         //    	 回显信息
    	   privilegeIds=new Long[role.getPrivileges().size()];
    	   int index=0;
    	   for(Privilege privilege:role.getPrivileges()){
    		   getPrivilegeIds()[index++]=privilege.getId();
    	   }
    	/*  privilegeIds=new Long[role.getPrivileges().size()];
   		  int index = 0;
   		  for (Privilege privilege : role.getPrivileges()) {
   			getPrivilegeIds()[index++] = privilege.getId();
   		  }*/

    	   return "setPrivilegeUI";
       }
       
       
       public String setPrivilege() throws Exception{
    	  
    	   Role role=roleService.getById(model.getId());
    	 
    	   List<Privilege> privilegeList=privilegeService.getByIds(privilegeIds);
    	   role.setPrivileges(new HashSet<Privilege>(privilegeList));
    	   
    	   roleService.update(role);
    	   return "tolist";
       }

       
	public Long[] getPrivilegeIds() {
		return privilegeIds;
	}

	public void setPrivilegeIds(Long[] privilegeIds) {
		this.privilegeIds = privilegeIds;
	}
}
